<script setup>
import TopicExploreListItem from './TopicExploreListItem.vue'
import { useTopicListQuery, useHotTopicListQuery } from '@/composables/useTopicDataQuery'
import { watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()

const props = defineProps({
  classId: Number,
})

const { data: hotTopicList } = useHotTopicListQuery({ page: 1, limit: 10 })

const classId = computed(() => props.classId)

const { data: topicData, fetchNextPage, hasNextPage, isFetching } = useTopicListQuery(classId)
// 将分页数据扁平化为一个数组
const flattenedData = computed(() => topicData?.value?.pages.flatMap((page) => page.result?.data) ?? [])

const loadMore = () => {
  if (isFetching.value) return
  fetchNextPage()
}

const displayList = computed(() => {
  if (classId.value == 0) {
    return hotTopicList.value?.pages?.flatMap((page) => page.result?.data) ?? []
  }
  return flattenedData.value
})

const emit = defineEmits(['displayList'])

// 深度监听 route，且页面初始化时也派发
function emitDisplayList() {
  if (classId.value == 0) {
    const data = hotTopicList.value?.pages?.flatMap((page) => page.result?.data) ?? []
    emit('displayList', data)
  } else {
    const data = flattenedData.value
    emit('displayList', data)
  }
}

onMounted(() => {
  emitDisplayList()
})

watch(
  () => route.fullPath,
  () => {
    emitDisplayList()
  },
  { immediate: false, deep: true }
)
watch(displayList, (newVal) => {
  // console.log(newVal);
  emit('displayList', newVal)

})
</script>

<template>
  <div v-show="classId != 0">

    <div v-if="displayList.length === 0" class="empty-topic-list flex flex-col items-center justify-center py-16">
      <img src="/src/assets/empty-expert.svg" alt="暂无主题" class="w-32 h-32 mb-4 opacity-80" />
      <div class="text-xl font-semibold text-slate-400 mb-1">暂无主题</div>
      <div class="text-base text-[--text-2]">当前标签下暂无主题，请创建新主题。</div>
    </div>

    <div v-else v-infinite-scroll="loadMore" :infinite-scroll-disabled="isFetching || !hasNextPage"
      :infinite-scroll-distance="5"
      class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 3xl:grid-cols-5 4xl:grid-cols-6 gap-6">
      <TopicExploreListItem v-for="item in displayList" :item="item" :key="item.id" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.empty-topic-list {
  min-height: 320px;
}
</style>
